package com.ecas.core.base.controller.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;

/**
 *  @description:
 *  @author devonmusa
 *  @datetime 2018/6/15 1:21
 *  @since 1.0.0
 */
@Aspect
@Component
public class ControllerAspect {
    private static final Logger LOG = LoggerFactory.getLogger(ControllerAspect.class);

    @Pointcut("execution( public * com.ecas.controller..*(..))")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object process(ProceedingJoinPoint joinPoint) {

        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        StringBuilder logInfo = new StringBuilder("Controller:");
        logInfo.append(className)
                .append(",methodName:").append(methodName)
                .append(",args:").append(Arrays.toString(args));
        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            result = joinPoint.proceed();
            if (result instanceof ModelAndView || result instanceof JSONObject) {
                logInfo.append("Response:").append(result.toString());
            }
        } catch (Throwable throwable) {
            LOG.error("Exception:", throwable);
        } finally {
            long endTime = System.currentTimeMillis();
            logInfo.append(",CostTime:").append(endTime - startTime).append("ms");
            LOG.info(logInfo.toString());
        }
        return result;

    }
}
